/**
 * 
 */
package com.beta.common.beanmapper;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import ma.glasnost.orika.Converter;
import ma.glasnost.orika.Mapper;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.ConfigurableMapper;

/**
 * @author vector
 *
 */
public class SpringConfigurableMapper extends ConfigurableMapper implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	private MapperFactory mapperFactory;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.springframework.context.ApplicationContextAware#setApplicationContext
	 * (org.springframework.context.ApplicationContext)
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
		addSpringMappers();
        addSpringConverter();
	}

	@Override
    protected void configure(MapperFactory factory) {
        super.configure(factory);
        this.mapperFactory = factory;
    }

	private void addSpringMappers() {
		@SuppressWarnings("rawtypes")
		final Map<String, Mapper> mappers = applicationContext.getBeansOfType(Mapper.class);
		for (final Mapper<?, ?> mapper : mappers.values()) {
			this.mapperFactory.registerMapper(mapper);
		}
	}

	private void addSpringConverter() {
		@SuppressWarnings("rawtypes")
		final Map<String, Converter> converters = applicationContext.getBeansOfType(Converter.class);
		for (final Converter<?, ?> converter : converters.values()) {
			this.mapperFactory.getConverterFactory().registerConverter(converter);
		}
	}

}
